package de.szut.sudoku.cui;

import java.util.Scanner;

/**
 * Class for inputting a value on the CUI
 * 
 * @author dqi12huisinga
 * 
 */
public class ValueInput {
	private int inputxPosition;
	private int inputyPosition;
	private int value;
	private boolean inputHasError;
	private Scanner scanner;

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	public boolean isInputHasError() {
		return inputHasError;
	}

	public void setInputHasError(boolean inputHasError) {
		this.inputHasError = inputHasError;
	}

	public int getInputxPosition() {
		return inputxPosition;
	}

	public void setInputxPosition(int inputxPosition) {
		this.inputxPosition = inputxPosition;
	}

	public int getInputyPosition() {
		return inputyPosition;
	}

	public void setInputyPosition(int inputyPosition) {
		this.inputyPosition = inputyPosition;
	}

	/**
	 * Checks if the input is correct
	 * 
	 * @param inputString
	 * @return
	 */
	private boolean isInputCorrect(String inputString) {
		int value;
		// checks if the input is an integer
		try {
			value = Integer.valueOf(inputString);
		} catch (NumberFormatException e) {
			return false;
		}
		// checks if the input is in the range 1,9
		if (value < 0 || value > 9) {
			return false;
		}
		return true;
	}

	/**
	 * Inputs a value
	 */
	public void inputValue() {
		String inputString;
		System.out
				.println("X-Position of the value that is supposed to be changed:");
		// gets the x position
		inputString = scanner.next();
		if (isInputCorrect(inputString)) {
			inputxPosition = Integer.valueOf(inputString);
			System.out
					.println("Y-Position of the value that is supposed to be changed:");
			// gets the y position
			inputString = scanner.next();
			if (isInputCorrect(inputString)) {
				inputyPosition = Integer.valueOf(inputString);
				System.out.println("New value of (" + inputxPosition + "|"
						+ inputyPosition + "):");
				// gets the value
				inputString = scanner.next();
				if (isInputCorrect(inputString)) {
					value = Integer.valueOf(inputString);
					inputHasError = false;
				} else {
					setInputHasError(true);
				}
			} else {
				setInputHasError(true);
			}
		} else {
			setInputHasError(true);
		}

	}

	/**
	 * Closing the scanner to assure that there are no leaks
	 */
	public void closeScanner() {
		scanner.close();
	}

	public ValueInput() {
		scanner = new Scanner(System.in);
		setInputHasError(false);
	}
}
